package com.innovation.ic.cc.base.service.cc.impl;

import cn.hutool.json.XML;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.HttpUtils;
import com.innovation.ic.b1b.framework.util.MiscUtil;
import com.innovation.ic.cc.base.mapper.cc.SmsInfoMapper;
import com.innovation.ic.cc.base.model.cc.SmsInfo;
import com.innovation.ic.cc.base.pojo.constant.Constants;
import com.innovation.ic.cc.base.pojo.constant.LoginConstants;
import com.innovation.ic.cc.base.pojo.constant.SmsConstants;
import com.innovation.ic.cc.base.pojo.enums.SmsStatusEnum;
import com.innovation.ic.cc.base.pojo.enums.SmsTemplateEnum;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.service.cc.SmsInfoService;
import com.innovation.ic.cc.base.value.SmsParamConfig;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author swq
 * @desc SmsInfoService的实现类
 * @time 2023年2月7日10:56:28
 */
@Service
@Transactional
public class SmsInfoServiceImpl extends ServiceImpl<SmsInfoMapper, SmsInfo> implements SmsInfoService {
    private static final Logger logger = LoggerFactory.getLogger(SmsInfoServiceImpl.class);

    @Resource
    private SmsInfoMapper smsInfoMapper;

    @Resource
    private SmsParamConfig smsParamConfig;


    /**
     * 通过ERP发送短信验证码
     *
     * @param mobile 手机号
     * @return 返回发送结果
     */
    @Override
    public ServiceResult<JSONObject> sendSmsCodeByErp(String mobile) {
        ServiceResult<JSONObject> serviceResult = new ServiceResult<>();
        Boolean result = Boolean.FALSE;
        String message = null;
        Integer code = null;

        // 发送短信参数
        String param = SmsConstants.PHONE_FIELD + LoginConstants.EQUAL_SIGN + mobile;

        // 通过ERP发送短信验证码
        String sendResult = HttpUtils.sendGet(smsParamConfig.getErpSendSmsUrl(), param, null);
        if (!Strings.isNullOrEmpty(sendResult)) {
            JSONObject json = (JSONObject) JSONObject.parse(sendResult);
            if (json != null) {
                Integer status = json.getInteger(LoginConstants.STATUS_FIELD);
                if (status == HttpStatus.SC_OK) {
                    message = "短信发送成功";
                    logger.info(message);
                    result = Boolean.TRUE;
                    code = json.getInteger(LoginConstants.DATA);
                }
                if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    message = json.getString(LoginConstants.MSG);
                    logger.info(message);
                    result = Boolean.FALSE;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(Constants.RESULT, result);
                    serviceResult.setSuccess(result);
                    serviceResult.setMessage(message);
                    return serviceResult;
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put(Constants.RESULT, result);
        jsonObject.put(LoginConstants.CODE_FIELD, code);

        serviceResult.setSuccess(result);
        serviceResult.setResult(jsonObject);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 发送短信验证码
     *
     * @param type   短信验证码类型,1: 登录
     * @param mobile 手机号
     * @return 返回发送短信验证码结果
     */
    @Override
    public ServiceResult<Boolean> send(String type, String mobile) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = Boolean.FALSE;
        String message = null;

        try {
            // 生成随机短信验证码
            String smsCode = MiscUtil.randomNum(smsParamConfig.getLength(), "SHA1PRNG");
            // 发送短信
            String sendMsgResult;
            String smsTemplate = SmsTemplateEnum.getDesc(type);
            smsTemplate = smsTemplate.replace(SmsConstants.SMS_CODE, smsCode);
            logger.info("发送给手机:[{}]的短信内容为:[{}]", mobile, smsTemplate);
            if (smsParamConfig.getEnable()) {
                sendMsgResult = sendMsg(mobile, smsTemplate);
            } else {
                sendMsgResult = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CSubmitState xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">  <State>0</State>  <MsgID>2208051555129749833</MsgID>  <MsgState>提交成功</MsgState>  <Reserve>1</Reserve></CSubmitState>\n" +
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?><CSubmitState xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">  <State>0</State>  <MsgID>2208051555129749833</MsgID>  <MsgState>提交成功</MsgState>  <Reserve>1</Reserve></CSubmitState>";
            }
            cn.hutool.json.JSONObject json = XML.toJSONObject(sendMsgResult);
            logger.info("短信发送结果为[{}]" + json.toString());
            if (json.get(SmsConstants.SMS_SUBMIT_STATE) != null) {
                JSONArray jsonArray = (JSONArray) json.get(SmsConstants.SMS_SUBMIT_STATE);
                if (jsonArray != null && jsonArray.size() > 0) {
                    JSONObject stateJson = (JSONObject) jsonArray.get(0);
                    if (stateJson != null && stateJson.get(SmsConstants.STATE) != null) {
                        Integer state = (Integer) stateJson.get(SmsConstants.STATE);
                        if (state == 0) {
                            message = "短信发送成功";
                            logger.info(message);
                            result = Boolean.TRUE;

                            // 向数据库中插入短信发送信息
                            insertSmsInfoData(type, mobile, smsCode);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info("发送短信验证码功能出现问题,原因:", e);
            message = "验证码发送失败,请重试";
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 发送短信
     *
     * @param mobile 手机号
     * @param msg    短信内容
     * @return 发送短息发送结果
     */
    private String sendMsg(String mobile, String msg) {
        String name = smsParamConfig.getName();
        String password = smsParamConfig.getPassword();
        String smsCode = smsParamConfig.getSmsCode();

        String param = SmsConstants.SMS_NAME + "=" + name +
                "&" + SmsConstants.SMS_PWD + "=" + password +
                "&" + SmsConstants.SMS_SCORPID + "=" + "" +
                "&" + SmsConstants.SMS_SPRDID + "=" + smsCode +
                "&" + SmsConstants.SMS_MOBILE + "=" + mobile +
                "&" + SmsConstants.SMS_MSG + "=" + msg;
        return HttpUtils.sendGet(smsParamConfig.getUrl(), param, null);
    }

    /**
     * 向数据库中插入短信发送信息
     */
    private void insertSmsInfoData(String type, String mobile, String smsCode) {
        SmsInfo smsInfo = new SmsInfo();
        //smsInfo.setId(IdUtils.getIdByPkName(SmsConstants.SMS_PK_NAME));
        smsInfo.setMobile(mobile);
        smsInfo.setType(type);
        smsInfo.setSmsCode(smsCode);
        smsInfo.setCreateTime(new Date(System.currentTimeMillis()));
        smsInfo.setVerifyTimes(0);
        smsInfo.setSmsStatus(SmsStatusEnum.READY.getCode());
        smsInfoMapper.insert(smsInfo);
    }
}